using System;
using System.Collections.Generic;
using BBX.Common;
using BBX.Config;
using BBX.Entity;
using BBX.Forum;

namespace BBX.Web
{
    public class invite : PageBase
    {
        public String inviteurl = "";
        private IUser userinfo;
        public Invitation invitecodeinfo;
        public String invitecode = DNTRequest.GetQueryString("Code");
        public String action = DNTRequest.GetQueryString("action");
        public String userscore = "";
        public String invitecodeprice = "";
        public IList<Invitation> invitecodelist = new List<Invitation>();
        public Int32 invitecodecount;
        public Int32 pageindex = DNTRequest.GetQueryInt("page", 1);
        public String pagenumber = "";
        public Int32 pagecount;
        public String emailpreview = "";
        public String usersaid = Utils.HtmlEncode(Utils.RemoveHtml(DNTRequest.GetString("usersaid")));
        public InvitationConfigInfo invitationconfiginfo = InvitationConfigInfo.Current;
        public Boolean isuseusersaid;
        public String[] extcreditnames = Scoresets.GetValidScoreName();
        public String[] extcreditunits = Scoresets.GetValidScoreUnit();
        public String avatarSmall = "";
        public String avatarMedium = "";
        public String avatarLarge = "";
        public Int32 datediff;

        protected override void ShowPage()
        {
            pagetitle = "邀请注册";
            if (!Utils.InArray(config.Regstatus.ToString(), "2,3"))
            {
                base.AddErrLine("当前站点没有开启邀请功能！");
                return;
            }
            if (userid > 0)
            {
                if (action == "floatwinemail")
                {
                    return;
                }
                avatarSmall = Avatars.GetAvatarUrl(userid, AvatarSize.Small);
                avatarMedium = Avatars.GetAvatarUrl(userid, AvatarSize.Medium);
                avatarLarge = Avatars.GetAvatarUrl(userid, AvatarSize.Large);
                userinfo = Users.GetUserInfo(userid);
                if (config.Regstatus == 2)
                {
                    invitecodeinfo = Invitation.GetInviteCodeByUid(userid);
                    if (invitecodeinfo != null)
                    {
                        inviteurl = GetUserInviteUrl(invitecodeinfo.Code, false);
                        userscore = GetUserInviteScore(invitecodeinfo.SuccessCount);
                        usersaid = string.Format("邀请附言:<div id=\"usersaidinemail\">{0}</div>", usersaid);
                        if (!ispost)
                        {
                            CreateEmailPreview();
                        }
                    }
                }
                else
                {
                    invitecodecount = Invitation.GetUserInviteCodeCount(userid);
                    invitecodelist = Invitation.GetUserInviteCodeList(userid, pageindex);
                    invitecodeprice = GetInviteCodePrice();
                    pagecount = (invitecodecount - 1) / 10 + 1;
                    pagenumber = Utils.GetPageNumbers(pageindex, pagecount, "invite.aspx", 8);
                }
                if (ispost)
                {
                    String a;
                    if ((a = action) == null)
                    {
                        return;
                    }
                    if (!(a == "createcode"))
                    {
                        if (!(a == "convertcode"))
                        {
                            if (!(a == "buycode"))
                            {
                                if (!(a == "floatwinemailsend"))
                                {
                                    return;
                                }
                                SendEmail();
                            }
                            else
                            {
                                BuyInviteCode();
                            }
                        }
                        else
                        {
                            ConvertInviteCode();
                        }
                    }
                    else
                    {
                        CreateInviteCode();
                    }
                }
            }
            if (userid == -1 && !String.IsNullOrEmpty(invitecode))
            {
                //this.invitecodeinfo = Invitation.GetInviteCodeByCode(this.Code);
                invitecodeinfo = Invitation.FindByCode(invitecode);
            }
        }

        public void CreateInviteCode()
        {
            if (config.Regstatus == 2 && invitationconfiginfo.InviteCodeUserCreatePerDay > 0 && Invitation.GetTodayUserCreatedInviteCode(userid) >= invitationconfiginfo.InviteCodeUserCreatePerDay)
            {
                base.AddErrLine("您今天申请邀请码的数量过多，请明天再试!");
                return;
            }
            if (invitecodeinfo == null)
            {
                Invitation.CreateInviteCode(userinfo);
                base.SetUrl("invite.aspx");
                base.SetMetaRefresh();
                base.SetShowBackLink(false);
                base.AddMsgLine("创建邀请码成功");
            }
        }

        public void ConvertInviteCode()
        {
            if (config.Regstatus == 2 && invitecodeinfo != null)
            {
                Invitation.ConvertInviteCodeToCredits(invitecodeinfo, invitationconfiginfo.InviteCodePayCount);
                //Invitation.DeleteInviteCode(this.invitecodeinfo.InviteId);
                invitecodeinfo.Delete();
                var strinfo = (invitecodeinfo.SuccessCount - invitationconfiginfo.InviteCodePayCount > -1) ? "兑换成功" : "删除成功";
                base.SetUrl("invite.aspx");
                base.SetMetaRefresh();
                base.SetShowBackLink(false);
                base.AddMsgLine(strinfo);
            }
        }

        public void SendEmail()
        {
            var list = new List<String>(Utils.SplitString(DNTRequest.GetString("email"), ","));
            if (String.IsNullOrEmpty(invitecode))
            {
                base.AddErrLine("丢失参数导致邮件发送失败，请检查本地杀毒软件设置");
                return;
            }
            //this.invitecodeinfo = Invitation.GetInviteCodeByCode(this.Code);
            invitecodeinfo = Invitation.FindByCode(invitecode);
            var num = 0;
            foreach (var current in list)
            {
                if (!string.IsNullOrEmpty(current) && Utils.IsValidEmail(current))
                {
                    if (Emails.SendEmailNotify(current, "来自您的好友:" + invitecodeinfo.Creator + "的邀请!", string.Format(invitationconfiginfo.InvitationEmailTemplate, new Object[]
                    {
                        current,
                        userid,
                        invitecodeinfo.Creator,
                        GetUserInviteUrl(invitecodeinfo.Code, true),
                        config.Forumtitle,
                        !String.IsNullOrEmpty(usersaid) ? usersaid : "",
                        rooturl,
                        avatarSmall,
                        avatarMedium,
                        avatarLarge
                    })))
                    {
                        num++;
                    }
                    if (num > 19)
                    {
                        break;
                    }
                }
            }
            if (num > 0)
            {
                base.AddMsgLine("成功发送" + num.ToString() + "封Email");
                return;
            }
            base.AddErrLine("发送失败，请检查Email地址是否正确");
        }

        public void BuyInviteCode()
        {
            if (invitecodecount >= invitationconfiginfo.InviteCodeMaxCountToBuy)
            {
                base.AddErrLine("您所拥有的邀请码数量超过了系统上限，无法再购买");
                return;
            }
            var array = Utils.SplitString(invitationconfiginfo.InviteCodePrice, ",");
            var array2 = new Single[8];
            for (var i = 0; i < 8; i++)
            {
                array2[i] = (Single)array[i].ToDouble() * -1f;
            }
            if (CreditsFacade.UpdateUserExtCredits(userid, array2, false) > 0)
            {
                CreateInviteCode();
                return;
            }
            var str = "";
            if (EPayments.IsOpenEPayments())
            {
                str = "<br/><span><a href=\"usercpcreditspay.aspx\">点击充值积分</a></span>";
            }
            base.AddErrLine("积分不足，无法购买邀请码" + str);
        }

        public String GetUserInviteUrl(String code, Boolean isCreateLink)
        {
            if (isCreateLink)
            {
                return string.Format("<a href=\"{0}\" target=\"_blank\">{0}</a>", rooturl + "invite.aspx?Code=" + code);
            }
            return rooturl + "invite.aspx?Code=" + code;
        }

        public String GetUserInviteScore(Int32 mount)
        {
            var num = (Single)(mount - invitationconfiginfo.InviteCodePayCount);
            if (num > 0f)
            {
                var userExtCredits = Scoresets.GetUserExtCredits(CreditsOperationType.Invite);
                var text = "";
                for (var i = 0; i < userExtCredits.Length; i++)
                {
                    if ((Double)userExtCredits[i] != 0.0)
                    {
                        text += string.Format("{0}:{1}{2} ;", extcreditnames[i + 1], userExtCredits[i] * (Single)mount, extcreditunits[i + 1]);
                    }
                }
                return text;
            }
            return "该邀请码尚未达到兑换条件!";
        }

        public String GetInviteCodePrice()
        {
            var text = "";
            var array = Utils.SplitString(invitationconfiginfo.InviteCodePrice, ",");
            for (var i = 0; i < 8; i++)
            {
                if (array[i].ToDouble() != 0f)
                {
                    text += string.Format("{0}:{1}{2} ,", extcreditnames[i + 1], array[i], extcreditunits[i + 1]);
                }
            }
            if (!(text != ""))
            {
                return "暂无定价;";
            }
            return text;
        }

        public void CreateEmailPreview()
        {
            isuseusersaid = (invitationconfiginfo.InvitationEmailTemplate.IndexOf("{5}") > 0);
            emailpreview = string.Format(invitationconfiginfo.InvitationEmailTemplate, new Object[]
            {
                "[friend]",
                userid,
                invitecodeinfo.Creator,
                GetUserInviteUrl(invitecodeinfo.Code, true),
                config.Forumtitle,
                usersaid,
                rooturl,
                avatarSmall,
                avatarMedium,
                avatarLarge
            });
        }

        public String InviteCodeExpireTip(DateTime time)
        {
            datediff = (Int32)(time - DateTime.Now).TotalHours;
            if (datediff < 0)
            {
                String str;
                switch (datediff / 24)
                {
                    case 0:
                        str = "明天过期";
                        break;

                    case 1:
                        str = "后天过期";
                        break;

                    default:
                        str = (datediff / 24 + 1).ToString() + "天后过期";
                        break;
                }
                return "您的邀请链接会在" + str;
            }
            return "<font color=red><b>您的邀请链接已过期</b></font>";
        }

        public String CreateUserExtCreditsStr()
        {
            var text = "";
            var format = " {0}:{1}{2} ;";
            if (extcreditnames[1] != string.Empty)
            {
                text += string.Format(format, extcreditnames[1], userinfo.ExtCredits1, extcreditunits[1]);
            }
            if (extcreditnames[2] != string.Empty)
            {
                text += string.Format(format, extcreditnames[2], userinfo.ExtCredits2, extcreditunits[2]);
            }
            if (extcreditnames[3] != string.Empty)
            {
                text += string.Format(format, extcreditnames[3], userinfo.ExtCredits3, extcreditunits[3]);
            }
            if (extcreditnames[4] != string.Empty)
            {
                text += string.Format(format, extcreditnames[4], userinfo.ExtCredits4, extcreditunits[4]);
            }
            if (extcreditnames[5] != string.Empty)
            {
                text += string.Format(format, extcreditnames[5], userinfo.ExtCredits5, extcreditunits[5]);
            }
            if (extcreditnames[6] != string.Empty)
            {
                text += string.Format(format, extcreditnames[6], userinfo.ExtCredits6, extcreditunits[6]);
            }
            if (extcreditnames[7] != string.Empty)
            {
                text += string.Format(format, extcreditnames[7], userinfo.ExtCredits7, extcreditunits[7]);
            }
            if (extcreditnames[8] != string.Empty)
            {
                text += string.Format(format, extcreditnames[8], userinfo.ExtCredits8, extcreditunits[8]);
            }
            return text.TrimEnd(';');
        }
    }
}